package cn.ml.ssmdemo.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class FileUploadController {

    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        //保存
        file.transferTo(new File("D:\\1_JAVA\\Spring-Upload",file.getOriginalFilename()));
        return "redirect:download";
    }

    @GetMapping("/download")
    public String download(ModelMap map){
        File file = new File("D:\\1_JAVA\\Spring-Upload");
        map.addAttribute("files",file.list());
        return "download";
    }


    //111.下载
    /*@RequestMapping(value = "/download",params = {"file"}) //必须传参file
    public void download(HttpServletResponse response,String file) throws IOException {
        InputStream in = new FileInputStream(new File("D:\\1_JAVA\\Spring-Upload",file));
        OutputStream out = response.getOutputStream();
        response.setContentType("application/octet-stream");
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename="+file); //点击下载时使用弹出式
        byte[] buffer = new byte[1024];
        while (true){
            int n = in.read(buffer);
            if(n == -1){
                break;
            }
            out.write(buffer,0,n);
            out.flush();
        }
        out.close();
        in.close();
    }*/
    //222.下载
    @RequestMapping(value = "/download",params = {"file"}) //必须传参file
    public ResponseEntity<FileSystemResource> download(String file){

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE,"application/octet-stream");
        headers.add(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename="+file);
        FileSystemResource fileSystemResource = new FileSystemResource(new File("D:\\1_JAVA\\Spring-Upload",file));
        ResponseEntity<FileSystemResource> responseEntity = new ResponseEntity<>(fileSystemResource,headers, HttpStatus.OK);
        return responseEntity;
    }

}
